const { shippingCarSchema } = require("../../../db/model");
const express = require("express");
const { checkToken } = require("../../../utils/token");
const { modelAmend, modelCreate, modelDelete } = require("../../../db/dispose");

const shoppingCar = express.Router();

shoppingCar.post("/user/shoppingCar/add", async (req, res) => {
  const { body } = req;
  const { gsColorCode, sizeName, quantity } = body;
  try {
    if (gsColorCode && sizeName && quantity) {
      const { userId } = await checkToken(req, res);

      //查询封的接口返回的数据无法继承传参属性
      const results = await shippingCarSchema.findOne({
        userId,
        gsColorCode,
        sizeName,
      });
      if (results) {
        //如果有同类商品，修改数量
        await modelAmend(res, results, {
          quantity: results.quantity + quantity,
        });
        return;
      }
      await modelCreate(shippingCarSchema, { userId, ...body }, res);
      return;
    }
    res.json({
      code: 400,
      msg: "参数缺失",
      succeed: false,
    });
  } catch (error) {
    console.log(error);
    res.json({
      code: 500,
      msg: "服务器错误",
      succeed: false,
    });
  }
});

//查询用户购物车列表
shoppingCar.get("/user/shoppingCar/user_car_find", async (req, res) => {
  try {
    const { userId } = await checkToken(req, res);
    const result = await shippingCarSchema.find({ userId }).sort({ _id: -1 });
    res.json({
      code: 200,
      data: result || [],
      msg: "请求成功",
      success: true,
    });
  } catch (error) {
    console.log(error);
    res.json({
      code: 500,
      msg: "服务器错误",
      success: false,
    });
  }
});


//购物车商品移除
shoppingCar.post("/user/shoppingCar/user_car_remove", async (req, res) => {
  const { body } = req
  try {
    const { userId } = await checkToken(req, res);
    await modelDelete(shippingCarSchema, { userId, _id: body.commodityId }, res)

  } catch (error) {
    console.log(error);
    res.json({
      code: 500,
      msg: "服务器错误",
      success: false,
    });
  }
});

module.exports = shoppingCar;
